<template>
  <div class="rule-container">
    <div class="create-container">
      <auth-btn btnPerm="parking:rule:add_edit">
        <el-button type="primary" @click="openFeeRule">增加停车计费规则</el-button>
      </auth-btn>
      <el-button @click="exportExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <!-- :index 自定义序号 -->
        <el-table-column label="序号" type="index" :index="indexMethod" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上限(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式" :formatter="formatChargeType" />
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <auth-btn btnPerm="parking:rule:add_edit">
              <el-button size="mini" type="text" @click="editRule(scope.row.id)">编辑</el-button>
            </auth-btn>
            <auth-btn btnPerm="parking:rule:remove">
              <el-button size="mini" type="text" @click="delRule(scope.row.id)">删除</el-button>
            </auth-btn>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager" style="margin-top: 10px; float: right">
        <el-pagination
          :page-size="pageSize"
          layout="total, pager, next"
          :total="total"
          :current-page="page"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
    <!-- :属性.sync="变量"  等同于
         :属性="变量" + @updata:属性="xxx" -->
    <!-- 子组件通过 this.$emit('update:属性名',属性值) -->
    <AddRule ref="AddRule" :dialog-visible.sync="dialogVisible" @getList="getRuleList" />
    <!-- 接收子组件传来的 自定义事件 -->
  </div>
</template>

<script>
import { getRuleListAPI, delRuleAPI } from "@/api/carrule";
import { utils, writeFileXLSX } from "xlsx";
import AddRule from "./components/AddRule.vue";
export default {
  name: "Building",
  components: {
    AddRule,
  },
  data() {
    return {
      page: 1,
      pageSize: 2,
      ruleList: [],
      total: 0,
      dialogVisible: false,
    };
  },
  computed: {
    chargeMap() {
      return {
        duration: "时长收费",
        turn: "按次收费",
        partition: "分段收费",
      };
    },
  },
  created() {
    this.getRuleList();
  },
  methods: {
    // 编辑计费规则
    editRule(id) {
      this.dialogVisible = true;
      // 调用子组件方法
      this.$refs.AddRule.getRule(id);
    },
    // 删除计费规则
    delRule(id) {
      this.$confirm("您确定要删除该规则嘛？", "温馨提示")
        .then(async () => {
          await delRuleAPI(id);
          this.$message.success("删除成功");
          this.getRuleList();
        })
        .catch(() => {});
    },
    // 打开添加计费规则
    openFeeRule() {
      this.dialogVisible = true;
    },
    // 格式化收费方式
    formatChargeType(row, column, cellValue, index) {
      // row: 当前行数据
      // column: 当前列信息
      // cellValue: 当前单元格的值(即row[column.property])
      // index: 行索引
      return this.chargeMap[row.chargeType];
      // return this.chargeMap[];
    },
    // 导出excel
    exportExcel() {
      // 导出字段key/字段排序
      const tableHeaderKeys = [
        "ruleNumber",
        "ruleName",
        "freeDuration",
        "chargeCeiling",
        "chargeType",
        "ruleNameView",
      ];
      // 表头中文字段value
      const tableHeaderValues = [
        "计费规则编号",
        "计费规则名称",
        "免费时长(分钟)",
        "收费上线(元)",
        "计费方式",
        "计费规则",
      ];
      // 筛选需要导出的字段  list:[{ 需要的key:item[key]的value }, {}, ...]
      const list = this.ruleList.map((item) => {
        const obj = {};
        // 遍历需要键名/排序（注意forEach有序，提前在tableHeaderKeys中排序）
        tableHeaderKeys.forEach((key) => {
          // obj中的 键:值 = item中的 键:值
          if (key === "chargeType") {
            obj[key] = this.chargeMap[item[key]];
          } else {
            obj[key] = item[key];
          }
        });
        // 每次遍历返回一个对象
        return obj;
      });
      // 创建一个新的工作簿
      const workbook = utils.book_new();
      // 创建一个工作表 要求一个对象数组格式
      const worksheet = utils.json_to_sheet(list);
      // 把工作表添加到工作簿  Data为工作表名称
      utils.book_append_sheet(workbook, worksheet, "Data");
      // 改写表头
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: "A1" });
      // 导出方法进行导出
      writeFileXLSX(workbook, "计费规则.xlsx");
    },
    // 翻页
    handleCurrentChange(val) {
      this.page = val;
      this.getRuleList();
    },
    // 获取规则列表
    async getRuleList() {
      const {
        data: { rows, total },
      } = await getRuleListAPI({
        page: this.page,
        pageSize: this.pageSize,
      });
      this.ruleList = rows;
      this.total = total;
      const maxPage = Math.ceil(total / this.pageSize);
      if (this.page > maxPage && maxPage > 0) {
        this.params.page = maxPage;
        this.$message.warning("已自动跳转到最后一页");
        this.getCardList();
        return;
      }
    },
    // 格式化序号
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.pageSize;
    },
  },
};
</script>

<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}
.create-container {
  margin: 10px 0px;
}
</style>
